import { message } from 'ant-design-vue';
import { FormType } from '/@/enums/workflowEnum';
import { FormConfigItem, FormSettingItem, TableItem } from '/@/model/workflow/formSetting';
import { getCustomJson, getSystemJson } from '/@/utils/formSettings/formJson';
import { FormSchema } from '/@/components/Form';
import { randomTime } from '/@bpmn/util/random';
import { updateFormFieldIdRelevance } from './useUpdateAllFormInfo';
export const visitorsBookType = 'opinion'; //意见簿类型
export const hiddenComponentType = 'hiddenComponent'; //隐藏组件类型
export const titleType = 'title'; //标题类型
export const dividerType = 'divider'; //分割线类型
export const infoType = 'info'; //信息体
export const autoCodeType = 'auto-code'; //编码
export const buttonType = 'button'; //按钮
// 标题，分割线、信息体，按钮，编码，意见簿，只允许查看权限
const disableTypes = [
  visitorsBookType,
  titleType,
  dividerType,
  infoType,
  autoCodeType,
  buttonType,
  'qrcode', //二维码组件
]; //表单字段仅仅只有查看权限
// 开关，滑块，颜色选择，评分，图片 组件权限中，必填权限为disable
export const requiredDisabled = [
  visitorsBookType,
  titleType,
  dividerType,
  infoType,
  autoCodeType,
  buttonType,
  'switch',
  'slider',
  'rate',
  'picker-color',
  'image',
];
export const doNotShowControl = ['qrcode']; //表单设置不显示编辑和必填操作项的组件
export const doNotTypes = [visitorsBookType, titleType, dividerType, 'image', 'qrcode']; //不需要考虑的类型
export async function formPermissionList(list: Array<FormSettingItem>) {
  const returnList: Array<FormConfigItem> = [];
  if (list.length > 0) {
    for (let index = 0; index < list.length; index++) {
      const formConfig = await getFormConfig(list[index]);
      returnList.push(formConfig);
    }
  }
  return returnList;
}
export async function getFormConfig(item: {
  key?: string;
  formId: string;
  formName: string;
  formType: FormType;
  name?: string;
}) {
  const formId = item.formId;
  const formType = item.formType;
  const formName = item.formName;
  const name = item.name ? item.name : item.formName;
  const key = item.key ? item.key : 'form_' + item.formId + '_' + randomTime();
  const formConfig: FormConfigItem = {
    key,
    formType,
    formId,
    formName,
    name,
    showChildren: false,
    requiredAll: true,
    viewAll: true,
    editAll: true,
    children: [],
  };
  const schema = await getSchemasList(formId, formType);
  if (schema.length > 0) {
    formConfig.children = getSchemasConfig(schema);
  }
  return formConfig;
}
// 删除表单：表单中字段被删除：删除已引用该表单数据字段的所有配置
function updateFormDataRelevance(
  oldData: FormConfigItem,
  oldChildMap: Map<string, FormConfigItem>,
  newData: FormConfigItem,
) {
  const formKey = oldData.key;
  const oldChild = oldData.children;
  const newChildMap = new Map();
  const newChild = newData.children;
  if (newChild && Array.isArray(newChild)) {
    newChild.forEach((ele) => {
      if (ele.children.length > 0) {
        ele.children.forEach((item) => {
          newChildMap.set(item.tableName + item.key, item);
        });
      }
      newChildMap.set(ele.key, ele);
    });
  }

  // 旧表单的字段有，却在新表单中被上删除了，那么就要查找然后删除对应关联了
  if (oldChild && Array.isArray(oldChild)) {
    oldChild.forEach((oldItem) => {
      if (oldChildMap.has(oldItem.key) && !newChildMap.has(oldItem.key)) {
        updateFormFieldIdRelevance(formKey, oldItem.key);
      }
      //子表不会被关联
      // if (newItem.children.length > 0) {
      // }
    });
  }
}
export function compareFormInfo(oldData: FormConfigItem, newData: FormConfigItem) {
  const oldChildMap = new Map();
  const oldChild = oldData.children;
  if (oldChild && Array.isArray(oldChild)) {
    oldChild.forEach((old) => {
      if (old.children.length > 0) {
        old.children.forEach((item) => {
          oldChildMap.set(item.tableName + item.key, item);
        });
      }
      oldChildMap.set(old.key, old);
    });
  }
  const newChild = newData.children;
  const children: Array<TableItem> = [];
  updateFormDataRelevance(oldData, oldChildMap, newData);
  if (newChild && Array.isArray(newChild)) {
    newChild.forEach((newItem) => {
      const tempChildren: Array<TableItem> = [];
      if (newItem.children.length > 0) {
        newItem.children.forEach((item) => {
          tempChildren.push(
            oldChildMap.has(item.tableName + item.key)
              ? oldChildMap.get(item.tableName + item.key)
              : item,
          );
        });
      }
      newItem.children = tempChildren;
      newItem = oldChildMap.has(newItem.key)
        ? oldChildMap.get(newItem.key).type == 'form'
          ? newItem
          : oldChildMap.get(newItem.key)
        : newItem;
      children.push(newItem);
    });
  }
  newData.children = children;
  return newData;
}
export async function getSchemasList(formId: string, formType: FormType) {
  try {
    if (formType == FormType.CUSTOM) {
      const customJson: any = await getCustomJson(formId);
      if (customJson && customJson.schemas) {
        return customJson.schemas;
      }
    } else if (formType == FormType.SYSTEM) {
      const systemJson = await getSystemJson(formId);
      if (systemJson && systemJson?.schemas) {
        return systemJson.schemas;
      } else {
        message.error('读取系统表单失败');
        return [];
      }
    } else {
      return [];
    }
  } catch (error) {
    return [];
  }
}
function getSchemasConfig(list: FormSchema[]) {
  const arr: Array<TableItem> = [];
  if (list && list.length > 0) {
    list.forEach((ele1) => {
      if (['Card', 'Grid', 'Tab'].includes(ele1.component)) {
        if (ele1.children && ele1.children.length > 0) {
          ele1.children.forEach((ele2) => {
            if (ele2.list && ele2.list.length > 0) {
              arr.push(...getSchemasConfig(ele2.list));
            }
          });
        }
      } else if (ele1.component == 'SubForm') {
        arr.push(getTableConfig(ele1));
      } else if (ele1.component === 'OneForOne') {
        const obj: TableItem = getItemConfig(ele1);
        obj.isSubTable = true;
        obj.showChildren = false;
        const tempList: FormSchema[] = ele1.componentProps?.childSchemas || [];
        obj.children.push(...getSchemasConfig(tempList));
        arr.push(obj);
      } else {
        arr.push(getItemConfig(ele1));
      }
    });
  }
  return arr;
}
function getItemConfig(element) {
  const children: Array<TableItem> = [];
  let required = true;
  let view = true;
  let edit = true;
  let disabled = false;
  const type = element.type;

  if (disableTypes.includes(element.type)) {
    required = false;
    view = true;
    edit = false;
    disabled = true;
  }
  if (requiredDisabled.includes(element.type)) {
    required = false;
  }
  // 隐藏组件权限不要设置
  if (element.type === hiddenComponentType) {
    required = false;
    view = false;
    edit = false;
    disabled = true;
  }
  return {
    required,
    view,
    edit,
    disabled,
    tableName: '',
    fieldName: element.label,
    fieldId: element.field,
    isSubTable: false,
    showChildren: true,
    type,
    key: element.key,
    children,
  };
}
function getTableConfig(element) {
  const children: Array<TableItem> = [];
  if (
    element.componentProps &&
    element.componentProps.columns &&
    element.componentProps.columns.length > 0
  ) {
    element.componentProps.columns.forEach((ele2) => {
      if (ele2.dataIndex) children.push(getTableItemConfig(element.field, ele2));
    });
  }
  return {
    required: true,
    view: true,
    edit: true,
    disabled: false,
    isSubTable: true,
    showChildren: false,
    tableName: element.field,
    fieldName: element.label,
    fieldId: element.field,
    type: element.type,
    key: element.key,
    children,
  };
}
function getTableItemConfig(tableName: string, element) {
  return {
    required: true,
    view: true,
    edit: true,
    disabled: false,
    isSubTable: true,
    showChildren: false,
    tableName: tableName,
    fieldName: element.title,
    fieldId: element.dataIndex,
    type: element.type,
    key: element.key,
    children: [],
  };
}
